

from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from apps.areas import models
from apps.areas.models import Area

from apps.users.models import User

from utils.response_code import RETCODE

import logging

logger = logging.getLogger('django')
# from utils.views import LoginRequiredJSONMixin
class AreasView(View):
    """省市区数据"""

    def get(self, request):
        """提供省市区数据"""
        area_id = request.GET.get('area_id')

        if area_id is  None:
            # 读取省份缓存数据
            province_list = cache.get('province_list')
            if province_list is None:
            # 提供省份数据
                try:
                    # 查询省份数据
                    province = Area.objects.filter(parent__isnull=True)

                    # 序列化省级数据
                    province_list = []
                    for province_model in province:
                        province_list.append({'id': province_model.id,
                                              'name': province_model.name})
                except Exception as e:
                    logger.error(e)
                    return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '省份数据错误'})

                # 设置缓存
                cache.set('province', 'province_list', 24 * 3600)
                # 响应省份数据
                return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})
        else:
            sub_data = cache.get('sub_data')

            if sub_data is None:
                # 提供市或区数据
                cities = Area.objects.filter(parent_id=area_id)  # 查询市或区的父级 area_id 表示省id

                    # 序列化市或区数据
                sub_data = []
                for city in cities:
                    sub_data.append({'id': city.id,
                                     'name': city.name})

            cache.set('sub_data%s'%area_id,'sub_data',24*3600)
            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'sub_data': sub_data})
            # 响应市或区数据





